<template>
    <el-card class="box-card" shadow="never">
        <el-form ref="passwordFormRef" label-width="110px" :rules="rules" :model="formInline">
            <div class="form-items">
                <el-form-item label="请输入旧密码" prop="oldPassword">
                    <el-input v-model="formInline.oldPassword" type="password" placeholder="请输入旧密码" clearable />
                </el-form-item>
                <el-form-item label="请输入新密码" prop="newPassword">
                    <el-input v-model="formInline.newPassword" type="password" placeholder="请输入密码" clearable />
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input v-model="formInline.confirmPassword" type="password" placeholder="请再次输入密码" clearable />
                </el-form-item>
            </div>
            <div class="form-btns">
                <el-button type="primary" @click="confirmPassword">确定</el-button>
                <el-button>取消</el-button>
            </div>
        </el-form>
    </el-card>
</template>

<script setup>
import { updateUserPwd } from '@/api/system/user'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()

const formInline = reactive({
    newPassword: '',
    confirmPassword: '',
})
const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== formInline.newPassword) {
        callback(new Error("两次密码输入不匹配"))
    } else {
        callback()
    }
}
const rules = ref({
    oldPassword: [
        { required: true, message: "密码不能为空", trigger: "blur" }
    ],
    newPassword: [
        { required: true, message: "密码不能为空", trigger: "blur" }, { min: 5, max: 20, message: "密码长度必须介于 5 和 20 之间", trigger: "blur" }
    ],
    confirmPassword: [
        { required: true, message: "密码不能为空", trigger: "blur" }, { validator: validatePass, trigger: 'blur' }
    ],
})
const passwordFormRef = ref()
function confirmPassword() {
    passwordFormRef.value.validate((valid) => {
        if (valid) {
            updateUserPwd(formInline.oldPassword, formInline.newPassword).then(res => {
                if (res.code == 200) {
                    ElMessage({ message: res.msg, type: 'success' })
                }
            })
        } else {
            return false
        }
    })
}
defineExpose({
    passwordFormRef
})
</script>
<style scoped lang="scss">
.box-card {
    padding: 90px 100px;

    .form-items {
        margin-bottom: 50px;
    }

    .form-btns {
        display: flex;
        align-items: center;
        justify-content: center;

        .el-button {
            width: 154px;
        }
    }
}
</style>